# coding = utf-8
# 数值计算
import numpy as np
# 鼠标键盘操作
from pyautogui import *
# 图像操作
from PIL import Image
# OCR
from paddleocr import PaddleOCR, draw_ocr


def get_curtime(time_format = "%Y-%m-%d %H:%M:%S"):
    curTime = time.localtime()
    curTime = time.strftime(time_format, curTime)
    return curTime

def ocr_image_text(path = "", saveImg = False, printResult = False):
    '''
    图像文字识别
    :param path: 图片路径
    :param saveImg: 是否把结果存为图片
    :param printResult: 是否打印识别的结果
    :return:
    '''

    image = path

    # 图片路径为空，默认获取屏幕截图
    if image == "":
        image = screenshot() # 使用pyautogui进行截图操作
        image = np.array(image)
    else:
        # 不为空就打开图片
        image = Image.open(image).convert('RGB')
        image = np.array(image)

    ocr = PaddleOCR(use_angle_cls = True, lang = "ch")

    result = ocr.ocr(image, cls = True)
    if printResult is True:
        for line in result:
            for world in line:
                print(world)

    # 识别出来的文字保存为图片
    img_name = "ImageTextOcr-img-" + get_curtime("%Y%m%d%H%M%S") + ".jpg"
    if saveImg is True:
        boxes = [detection[0] for line in result for detection in line]
        txts = [detection[1][0] for line in result for detection in line]
        scores = [detection[1][1] for line in result for detection in line]
        image_show = draw_ocr(image, boxes, txts, scores)
        image_show = Image.fromarray(image_show)
        image_show.save(img_name)

    return result, img_name


def ocr_get_txt_position(path="", text=""):
    '''
    获取文字位置
    :param path: 图片路径，图片路径为空默认获取当前屏幕截图
    :param text: 筛选需要查找的内容，匹配所有位置
    :return: 返回位置信息
    '''
    result, image_path = ocr_image_text(path, saveImg= True)
    print("图片识别结果保存：", image_path)

    # 将结果列表的两个值分别存入两个list
    # 结果示例：[[[1768.0, 8.0], [1893.0, 8.0], [1893.0, 34.0], [1768.0, 34.0]], ('知如何切换pip的源', 0.9970300793647766)]
    pos_list = [detection[0][0] for line in result for detection in line]
    txt_list = [detection[1][0] for line in result for detection in line]

    # 用list存储文字和位置信息
    find_txt_position = []
    item = 0
    if text == "":
        find_txt_position = result
    else:
        for i in range(len(pos_list)):
            if text in txt_list[i]:
                find_txt_position.append(pos_list[i])
                item += 1
    print(find_txt_position)
    return find_txt_position


if __name__ == "__main__":

    # ocr_image_text(saveImg=True, printResult=True)

    # ocr_get_txt_position(text="自动财报解析系统")

    # 数据点击
    pos_list = ocr_get_txt_position(text="自动财报解析系统")
    if not pos_list:
        print(pos_list)
    else:
        pos_x, pos_y = pos_list[0]
        moveTo(pos_x, pos_y)
        click()









